package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseOriginal;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.OutMainConfig;
import com.isunland.managesystem.entity.SimpleTreeListParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.entity.ZTreeNodeListOriginal;
import com.isunland.managesystem.entity.rOutappMain;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.MyViewUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 对象功能:  出库子表界面
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/7/14 14:12
 */
public class RetailOutMainDetailFragment extends BaseFragment {

  @BindView(R.id.slv_moutbillNo) SingleLineView slvMoutbillNo;
  @BindView(R.id.slv_mcustomerName) SingleLineView slvMcustomerName;
  @BindView(R.id.slv_customerPhone) SingleLineView slvCustomerPhone;
  @BindView(R.id.slv_materialKindName) SingleLineView slvMaterialKindName;
  @BindView(R.id.slv_mcustomerDeptName) SingleLineView slvMcustomerDeptName;
  @BindView(R.id.slv_moutappmanName) SingleLineView slvMoutappmanName;
  @BindView(R.id.slv_moutappDate) SingleLineView slvMoutappDate;
  @BindView(R.id.slv_storageName) SingleLineView slvStorageName;
  @BindView(R.id.slv_deliveryDate) SingleLineView slvDeliveryDate;
  @BindView(R.id.slv_invoiceNo) SingleLineView slvInvoiceNo;
  @BindView(R.id.slv_moutCom) SingleLineView slvMoutCom;
  @BindView(R.id.slv_deliveryAddress) SingleLineView slvDeliveryAddress;
  @BindView(R.id.slv_remark) SingleLineView slvRemark;
  @BindView(R.id.slv_tSelfinfo1) SingleLineView slvTSelfinfo1;
  @BindView(R.id.slv_tSelfinfo2) SingleLineView slvTSelfinfo2;
  @BindView(R.id.slv_tSelfinfo3) SingleLineView slvTSelfinfo3;
  @BindView(R.id.slv_tSelfinfo4) SingleLineView slvTSelfinfo4;
  @BindView(R.id.slv_tSelfinfo5) SingleLineView slvTSelfinfo5;
  @BindView(R.id.slv_dSelfinfo1) SingleLineView slvDSelfinfo1;
  @BindView(R.id.slv_dSelfinfo2) SingleLineView slvDSelfinfo2;
  @BindView(R.id.slv_dSelfinfo3) SingleLineView slvDSelfinfo3;
  @BindView(R.id.slv_sSelfinfo1) SingleLineView slvSSelfinfo1;
  @BindView(R.id.slv_sSelfinfo2) SingleLineView slvSSelfinfo2;
  @BindView(R.id.slv_sSelfinfo3) SingleLineView slvSSelfinfo3;
  @BindView(R.id.slv_sSelfinfo4) SingleLineView slvSSelfinfo4;
  @BindView(R.id.slv_sSelfinfo5) SingleLineView slvSSelfinfo5;
  @BindView(R.id.slv_fSelfinfo1) SingleLineView slvFSelfinfo1;
  @BindView(R.id.slv_regStaffName) SingleLineView slvRegStaffName;
  @BindView(R.id.slv_regDate) SingleLineView slvRegDate;
  @BindView(R.id.slv_moutbillStatus) SingleLineView slvMoutbillStatus;
  @BindView(R.id.slv_moutdealmanName) SingleLineView slvMoutdealmanName;
  @BindView(R.id.slv_moutdealDate) SingleLineView slvMoutdealDate;
  @BindView(R.id.slv_moutconfmanName) SingleLineView slvMoutconfmanName;
  @BindView(R.id.ll_rootConfig) LinearLayout llRootConfig;
  @BindView(R.id.slv_invoiceType) SingleLineView slvInvoiceType;
  @BindView(R.id.slv_invoiceDesc) SingleLineView slvInvoiceDesc;

  /*判断来自哪个出库单*/
  public static final int TOOL = 1;//工器具领用
  public static final int SALE = 2;//零购出库
  public static final int MATERIAL = 3;//生产原材料
  public static final int ORDER = 4;//销售订单

  private int SAVE = 0;
  private int RUN = 1;
  private final int ADD = 2;
  private final int NEW = 3;
  private final int SUB = 4;
  private final int PUBLISH = 5;
  private static final int REQUEST_DELETE = 6;
  private static final int REQUEST_SUBMIT = 7;
  protected static final int REQUEST_WAREHOUSE = 8;
  protected static final int REQUEST_PERSON = 9;
  protected static final int REQUEST_MATERIAL = 10;
  private static final int REQUEST_CUSTOMER = 11;
  private static final int REQUEST_FILE = 12;
  private static final int REQUEST_UPLOAD = 13;
  private int REQUEST_DEPT = 14;
  private int REQUEST_INVOICETYPE = 15;

  private rOutappMain mainContent;
  private int menuType;
  protected String salePersonId = "";
  protected String warehouseId = "";
  protected String materialKindCode = "";
  private int mtype;
  private CallBack mcallBack;
  private HashMap<String, OutMainConfig> mConfigMap;

  //回调接口
  public interface CallBack {
    void onRefresh(rOutappMain content, int type);
  }

  @Override public void onAttach(Activity activity) {
    super.onAttach(activity);
    mcallBack = (CallBack) getActivity();
  }

  @Override public void onDetach() {
    super.onDetach();
    mcallBack = null;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    mtype = mBaseParams.getType();
    mainContent = (rOutappMain) mBaseParams.getItem();
    if (BaseParams.TYPE_DETAIL == mtype) {
      //详情
      salePersonId = mainContent.getMoutappmanId();
      warehouseId = mainContent.getStorageId();
      materialKindCode = mainContent.getMaterialKindCode();
      String dataStatus = mainContent.getMoutbillStatus();
      if (DataStatus.NEW.equalsIgnoreCase(dataStatus) || DataStatus.ABORT.equalsIgnoreCase(
          dataStatus)) {
        menuType = NEW;
      } else if (DataStatus.WAIT_CHECK.equalsIgnoreCase(dataStatus)) {
        menuType = SUB;
      } else {
        menuType = PUBLISH;
      }
    }
    if (BaseParams.TYPE_ADD == mtype) {
      //添加
      menuType = ADD;
    }
  }

  private void volleyPostConfig(final View rootView) {
    String configUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_OUT_MAIN_CONFIG);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("docKindCode", mainContent.getMoutkindCode());//单据类别编码
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(configUrl, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        BaseOriginal<OutMainConfig> result =
            new Gson().fromJson(json, new TypeToken<BaseOriginal<OutMainConfig>>() {
            }.getType());
        ArrayList<OutMainConfig> mList = new ArrayList<>();
        if (Base.SUCCESS == result.getResult() && result.getRows() != null) {
          mList.addAll(result.getRows());
          mConfigMap = initConfigMap(mList);
          for (String tag : mConfigMap.keySet()) {
            SingleLineView lineView = (SingleLineView) rootView.findViewWithTag(tag);
            if (lineView != null) {
              OutMainConfig config = mConfigMap.get(tag);
              //设置显示和隐藏
              lineView.setVisibility(
                  "T".equalsIgnoreCase(config.getIfDisplayEdit()) ? View.VISIBLE : View.GONE);
              //设置标题
              lineView.setTextTitle(
                  (config.getFieldDesc().contains(":") || config.getFieldDesc().contains("："))
                      ? config.getFieldDesc() : MyStringUtil.connect(config.getFieldDesc(), "："));
              //设置是否可编辑,不可编辑可点击
              lineView.getTvContent().setFocusable("T".equalsIgnoreCase(config.getIfDisplay()));
              lineView.getTvContent().setClickable(true);
            }
          }
          llRootConfig.setVisibility(View.VISIBLE);
          MyUtils.dismissDialog();
        } else {
          ToastUtil.show("获取界面失败");
        }
      }
    });
  }

  private HashMap<String, OutMainConfig> initConfigMap(ArrayList<OutMainConfig> list) {
    HashMap<String, OutMainConfig> configMap = new HashMap<>();
    for (OutMainConfig item : list) {
      configMap.put(item.getFieldNameMap(), item);
    }
    return configMap;
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_retail_out_config_detail, container, false);
    ButterKnife.bind(this, rootView);
    //动态配置界面
    volleyPostConfig(rootView);
    return rootView;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    mConfigMap = new HashMap<>();

    slvMoutbillNo.setTextContent(mainContent.getMoutbillNo());
    slvMcustomerName.setTextContent(mainContent.getMcustomerName());
    slvCustomerPhone.setTextContent(mainContent.getCustomerPhone());
    slvMaterialKindName.setTextContent(mainContent.getMaterialKindName());
    slvMcustomerDeptName.setTextContent(mainContent.getMcustomerDeptName());
    slvMoutappmanName.setTextContent(mainContent.getMoutappmanName());
    slvMoutappDate.setTextContent(mainContent.getMoutappDate());
    slvStorageName.setTextContent(mainContent.getStorageName());
    slvDeliveryDate.setTextContent(mainContent.getDeliveryDate());//交货日期
    slvInvoiceType.setTextContent(mainContent.getInvoiceTypeName());//开票类型
    slvInvoiceDesc.setTextContent(mainContent.getInvoiceDesc());//开票描述
    slvInvoiceNo.setTextContent(mainContent.getInvoiceNo());//发票编号
    slvMoutCom.setTextContent(mainContent.getMoutCom());
    slvDeliveryAddress.setTextContent(mainContent.getDeliveryAddress());//交货地址
    slvRemark.setTextContent(mainContent.getRemark());
    /*自定义文本*/
    slvTSelfinfo1.setTextContent(mainContent.getTSelfinfo1());
    slvTSelfinfo2.setTextContent(mainContent.getTSelfinfo2());
    slvTSelfinfo3.setTextContent(mainContent.getTSelfinfo3());
    slvTSelfinfo4.setTextContent(mainContent.getTSelfinfo4());
    slvTSelfinfo5.setTextContent(mainContent.getTSelfinfo5());
      /*自定义时间*/
    slvDSelfinfo1.setTextContent(mainContent.getDSelfinfo1());
    slvDSelfinfo2.setTextContent(mainContent.getDSelfinfo2());
    slvDSelfinfo3.setTextContent(mainContent.getDSelfinfo3());
       /*自定义选择*/
    if (!TextUtils.isEmpty(mainContent.getSSelfinfo1())) {
      slvSSelfinfo1.setTextContent("T".equalsIgnoreCase(mainContent.getSSelfinfo1()) ? "是" : "否");
    }
    if (!TextUtils.isEmpty(mainContent.getSSelfinfo2())) {
      slvSSelfinfo2.setTextContent("T".equalsIgnoreCase(mainContent.getSSelfinfo2()) ? "是" : "否");
    }
    if (!TextUtils.isEmpty(mainContent.getSSelfinfo3())) {
      slvSSelfinfo3.setTextContent("T".equalsIgnoreCase(mainContent.getSSelfinfo3()) ? "是" : "否");
    }
    if (!TextUtils.isEmpty(mainContent.getSSelfinfo4())) {
      slvSSelfinfo4.setTextContent("T".equalsIgnoreCase(mainContent.getSSelfinfo4()) ? "是" : "否");
    }
    if (!TextUtils.isEmpty(mainContent.getSSelfinfo5())) {
      slvSSelfinfo5.setTextContent("T".equalsIgnoreCase(mainContent.getSSelfinfo5()) ? "是" : "否");
    }

     /*自定义附件*/
    slvFSelfinfo1.getIvLogo().setImageResource(R.drawable.add_address);
    slvFSelfinfo1.getTvContent().setTextColor(Color.BLUE);
    slvFSelfinfo1.getTvContent().setFocusable(false);
    slvFSelfinfo1.getTvContent().setClickable(true);
    slvFSelfinfo1.setTextContent(mainContent.getFSelfinfo1());

    slvRegStaffName.setTextContent(mainContent.getRegStaffName());
    slvRegDate.setTextContent(mainContent.getRegDate());
    MyUtils.switchShadowStutus(getActivity(), slvMoutbillStatus.getViewContent(),
        mainContent.getMoutbillStatus());
    slvMoutdealmanName.setTextContent(mainContent.getMoutdealmanName());
    slvMoutdealDate.setTextContent(mainContent.getMoutdealDate());

    //客户单位
    slvMcustomerName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        if (MATERIAL == mBaseParams.getFrom() || TOOL == mBaseParams.getFrom()) {
          //来自生产原材料和工器具: 客户对应部门
          getDeptKind();
        } else {
          //零售出库: 跳转到客户名录
          Intent i = new Intent(getActivity(), CustomerListChooseActivity.class);
          startActivityForResult(i, REQUEST_CUSTOMER);
        }
      }
    });
    //物料类别
    slvMaterialKindName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(new MaterielKindDialogFragment(), REQUEST_MATERIAL);
      }
    });
    //仓库
    slvStorageName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(new WareHouseDialogFragment(), REQUEST_WAREHOUSE);
      }
    });
    //销售员
    slvMoutappmanName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        Intent i = new Intent(getActivity(), AppointerListActivity.class);
        startActivityForResult(i, REQUEST_PERSON);
      }
    });
    //申报日期
    slvMoutappDate.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date())
            .setCallBack(new BaseYMDTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                slvMoutappDate.setTextContent(MyDateUtil.format(date, MyDateUtil.TYPE_DATE));
              }
            }));
      }
    });
    //开票类型
    slvInvoiceType.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(new InvoiceTypeDialogFragment(), REQUEST_INVOICETYPE);
      }
    });
    //交货日期
    slvDeliveryDate.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date())
            .setCallBack(new BaseYMDTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                slvDeliveryDate.setTextContent(MyDateUtil.format(date, MyDateUtil.TYPE_DATE));
              }
            }));
      }
    });
    //自定义时间
    slvDSelfinfo1.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date())
            .setCallBack(new BaseYMDTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                slvDSelfinfo1.setTextContent(MyDateUtil.format(date, MyDateUtil.TYPE_DATE));
              }
            }));
      }
    });
    slvDSelfinfo2.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date())
            .setCallBack(new BaseYMDTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                slvDSelfinfo2.setTextContent(MyDateUtil.format(date, MyDateUtil.TYPE_DATE));
              }
            }));
      }
    });
    slvDSelfinfo3.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date())
            .setCallBack(new BaseYMDTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                slvDSelfinfo3.setTextContent(MyDateUtil.format(date, MyDateUtil.TYPE_DATE));
              }
            }));
      }
    });

    //自定选择
    slvSSelfinfo1.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog((new IsOrNotDialogFragment()).setCallBack(new IsOrNotDialogFragment.CallBack() {
          @Override public void select(CustomerDialog content) {
            slvSSelfinfo1.setTextContent(content.getName());
            mainContent.setSSelfinfo1(content.getId());
          }
        }));
      }
    });
    slvSSelfinfo2.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog((new IsOrNotDialogFragment()).setCallBack(new IsOrNotDialogFragment.CallBack() {
          @Override public void select(CustomerDialog content) {
            slvSSelfinfo2.setTextContent(content.getName());
            mainContent.setSSelfinfo2(content.getId());
          }
        }));
      }
    });
    slvSSelfinfo3.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog((new IsOrNotDialogFragment()).setCallBack(new IsOrNotDialogFragment.CallBack() {
          @Override public void select(CustomerDialog content) {
            slvSSelfinfo3.setTextContent(content.getName());
            mainContent.setSSelfinfo3(content.getId());
          }
        }));
      }
    });

    slvSSelfinfo4.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog((new IsOrNotDialogFragment()).setCallBack(new IsOrNotDialogFragment.CallBack() {
          @Override public void select(CustomerDialog content) {
            slvSSelfinfo4.setTextContent(content.getName());
            mainContent.setSSelfinfo4(content.getId());
          }
        }));
      }
    });
    slvSSelfinfo5.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog((new IsOrNotDialogFragment()).setCallBack(new IsOrNotDialogFragment.CallBack() {
          @Override public void select(CustomerDialog content) {
            slvSSelfinfo5.setTextContent(content.getName());
            mainContent.setSSelfinfo5(content.getId());
          }
        }));
      }
    });
    //自定义附件
    slvFSelfinfo1.getIvLogo().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        //上传
        showDialog(ExtraUpLoadDialogFragment.newInstance("", ExtraUpLoadDialogFragment.TYPE_ALL),
            REQUEST_FILE);
      }
    });
    slvFSelfinfo1.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        //下载
        if (!TextUtils.isEmpty(slvFSelfinfo1.getTextContent())) {
          showDialog(ExtraDownLoadDialogFragment.newInstance("", mainContent.getFpSelfinfo1()));
        }
      }
    });

    //禁用所有view
    if (SUB == menuType || PUBLISH == menuType) {
      MyViewUtil.setEnableAll(false, slvMoutbillNo.getTvContent(), slvMcustomerName.getTvContent(),
          slvCustomerPhone.getTvContent(), slvMaterialKindName.getTvContent(),
          slvMcustomerDeptName.getTvContent(), slvMoutappmanName.getTvContent(),
          slvMoutappDate.getTvContent(), slvStorageName.getTvContent(),
          slvDeliveryDate.getTvContent(), slvInvoiceType.getTvContent(),
          slvInvoiceDesc.getTvContent(), slvInvoiceNo.getTvContent(), slvMoutCom.getTvContent(),
          slvDeliveryAddress.getTvContent(), slvRemark.getTvContent(), slvTSelfinfo1.getTvContent(),
          slvTSelfinfo2.getTvContent(), slvTSelfinfo3.getTvContent(), slvTSelfinfo4.getTvContent(),
          slvTSelfinfo5.getTvContent(), slvDSelfinfo1.getTvContent(), slvDSelfinfo2.getTvContent(),
          slvDSelfinfo3.getTvContent(), slvSSelfinfo1.getTvContent(), slvSSelfinfo2.getTvContent(),
          slvSSelfinfo3.getTvContent(), slvSSelfinfo4.getTvContent(), slvSSelfinfo5.getTvContent(),
          slvRegStaffName.getTvContent(), slvRegDate.getTvContent(),
          slvMoutbillStatus.getTvContent(), slvMoutdealmanName.getTvContent(),
          slvMoutdealDate.getTvContent(), slvMoutconfmanName.getTvContent());
      MyViewUtil.setVisibilityAll(View.GONE, slvFSelfinfo1.getIvLogo());
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (menuType) {
      //草稿状态：保存、保存并提交
      case ADD:
        inflater.inflate(R.menu.menu_save_submit, menu);
        menu.getItem(1).setTitle(R.string.submit);
        break;
      //草稿状态：保存、提交、删除
      case NEW:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        break;
      //提交状态：返回修改
      case SUB:
        inflater.inflate(R.menu.menu_stop, menu);
        break;
      //审核通过,已出库
      case PUBLISH:
        break;
      default:
        break;
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        //保存
        if (isCorrectInput()) {
          volleyPostSave(SAVE);
        }
        return true;
      case R.id.menu_item_submit:
        //保存并提交
        if (isCorrectInput()) {
          showDialog(BaseConfirmDialogFragment.newInstance(R.string.start_up_hint), REQUEST_SUBMIT);
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        showDialog(BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm), REQUEST_DELETE);
        return true;
      case R.id.menu_item_stop:
        // 返回修改
        volleyPostAbort();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private boolean isCorrectInput() {
    if (slvMaterialKindName.getVisibility() == View.GONE
        || slvMaterialKindName.getVisibility() == View.VISIBLE && !TextUtils.isEmpty(
        slvMaterialKindName.getTextContent())) {
      return true;
    } else {
      ToastUtil.show(R.string.notComplete);
      return false;
    }
  }

  /** 获取部门 */
  private void getDeptKind() {
    SimpleTreeListParams params = new SimpleTreeListParams();
    //noinspection unchecked
    ZTreeNode item = new ZTreeNode();
    item.setName("");
    item.setId("");
    //noinspection unchecked
    params.setItem(item);
    params.setChildField("id");
    params.setParentField("pid");
    params.setTitleField("name");
    params.setContentField("extParam2");
    params.setTitle("选择部门");
    params.setClassOriginal(ZTreeNodeListOriginal.class);
    params.setUrl(ApiConst.URL_QUERY_LIST_DEPT_TREE);
    params.setParamsNotEmpty(
        new ParamsNotEmpty().put("memberCode", CurrentUser.newInstance(mActivity).getMemberCode())
            .put("type", "mobile"));
    BaseVolleyActivity.newInstance(this, ZTreeListActivity.class, params, REQUEST_DEPT);
  }

  private void volleyPostSave(final int type) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RETAIL_OUT_SAVE);
    ParamsNotEmpty mparams = new ParamsNotEmpty();
    mparams.put("id", mainContent.getId());
    mparams.put("memberCode", mainContent.getMemberCode());
    mparams.put("moutappDate", mainContent.getMoutappDate());
    mparams.put("moutkindCode", mainContent.getMoutkindCode());
    mparams.put("sumPrice", mainContent.getSumPrice().toString());
    mparams.put("sumPriceString", mainContent.getSumPriceString());
    mparams.put("isOutAll", mainContent.getIsOutAll());

    mparams.put("moutbillNo", mainContent.getMoutbillNo());//订单编号

    mparams.put("mcustomerName", mainContent.getMcustomerName());//客户单位
    mparams.put("mcustomerId", mainContent.getMcustomerId());//客户单位
    mparams.put("customerPhone", slvCustomerPhone.getTextContent());//联系电话

    mparams.put("materialKindCode", mainContent.getMaterialKindCode());//物料
    mparams.put("materialKindName", mainContent.getMaterialKindName());

    mparams.put("mcustomerDeptName", slvMcustomerDeptName.getTextContent());//客户联系人

    mparams.put("moutappmanName", mainContent.getMoutappmanName());//销售员
    mparams.put("moutappmanId", mainContent.getMoutappmanId());

    mparams.put("moutappDate", slvMoutappDate.getTextContent());//订单日期

    mparams.put("storageName", mainContent.getStorageName());//仓库
    mparams.put("storageId", mainContent.getStorageId());

    mparams.put("deliveryDate", slvDeliveryDate.getTextContent());//交货日期

    mparams.put("invoiceType", mainContent.getInvoiceType());//开票类型code
    mparams.put("invoiceTypeName", mainContent.getInvoiceTypeName());//开票类型name
    mparams.put("invoiceDesc", slvInvoiceDesc.getTextContent());//开票描述
    mparams.put("invoiceNo", slvInvoiceNo.getTextContent());//发票编号

    mparams.put("deliveryAddress", slvDeliveryAddress.getTextContent());//交货地址
    mparams.put("moutCom", slvMoutCom.getTextContent());//订单概要
    mparams.put("remark", slvRemark.getTextContent());//备注

    mparams.put("tSelfinfo1", slvTSelfinfo1.getTextContent());//文本1
    mparams.put("tSelfinfo2", slvTSelfinfo2.getTextContent());//文本2
    mparams.put("tSelfinfo3", slvTSelfinfo3.getTextContent());//文本3
    mparams.put("tSelfinfo4", slvTSelfinfo4.getTextContent());//文本4
    mparams.put("tSelfinfo5", slvTSelfinfo5.getTextContent());//文本5

    mparams.put("dSelfinfo1", slvDSelfinfo1.getTextContent());//时间1
    mparams.put("dSelfinfo2", slvDSelfinfo2.getTextContent());//时间2
    mparams.put("dSelfinfo3", slvDSelfinfo3.getTextContent());//时间3

    mparams.put("sSelfinfo1", mainContent.getSSelfinfo1());//选择1
    mparams.put("sSelfinfo2", mainContent.getSSelfinfo2());//选择2
    mparams.put("sSelfinfo3", mainContent.getSSelfinfo3());//选择3
    mparams.put("sSelfinfo4", mainContent.getSSelfinfo4());//选择4
    mparams.put("sSelfinfo5", mainContent.getSSelfinfo5());//选择5

    mparams.put("fSelfinfo1", mainContent.getFSelfinfo1());//附件名
    mparams.put("fpSelfinfo1", mainContent.getFpSelfinfo1());//附件路径

    mparams.put("regStaffName", mainContent.getRegStaffName());
    mparams.put("regStaffId", mainContent.getRegStaffId());
    mparams.put("regDate", mainContent.getRegDate());
    mparams.put("moutbillStatus", mainContent.getMoutbillStatus());

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, mparams.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(json, SuccessMessage.class);
        if (message.getResult() == null) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {

          if (SAVE == type) {
            ToastUtil.show(R.string.success_operation);
            //保存
            if (BaseParams.TYPE_ADD == mtype) {
              //跳转到物料列表界面tab
              getActivity().setResult(Activity.RESULT_OK);
              mcallBack.onRefresh(mainContent, BaseParams.TYPE_DETAIL);
            } else {
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            }
          }
          if (RUN == type) {
            //保存并提交
            volleyPostSubmit();
          }
        }
        if (message.getResult() != null && SuccessMessage.FAILURE.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
        }
      }
    });
  }

  // 启动流程
  private void volleyPostSubmit() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SUBMIT_ORDER);
    HashMap<String, String> params = new HashMap<>();
    params.put("ifSaleOrder", "true");
    params.put("id", mainContent.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  private void volleyPostAbort() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("runId", mainContent.getRunId().toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  //删除
  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RETAIL_OUT_DEL);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mainContent.getId());
    params.put("deleteFormRecord", "true");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  public VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
        if (message.getResult() == null) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(R.string.success_operation);
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
        if (message.getResult() != null && SuccessMessage.FAILURE.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
        }
      }
    };
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    //客户单位
    if (requestCode == REQUEST_CUSTOMER) {
      String customerName = data.getStringExtra(CustomerListChooseFragment.CUSTOMER_NAME);
      String customerId = data.getStringExtra(CustomerListChooseFragment.CUSTOMER_ID);
      slvMcustomerName.setTextContent(customerName);
      mainContent.setMcustomerName(customerName);
      mainContent.setMcustomerId(customerId);
      return;
    }
    if (requestCode == REQUEST_DEPT) {
      //部门
      SimpleTreeListParams params = (SimpleTreeListParams) data.getSerializableExtra(EXTRA_PARAMS);
      ZTreeNode item = ((ZTreeNode) params.getItem());
      String name = item.getName();//项目组名
      slvMcustomerName.setTextContent(name);
      mainContent.setMcustomerName(name);
      mainContent.setMcustomerId(item.getId());
    }
    if (requestCode == REQUEST_MATERIAL) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      String materialKindName = customer.getName();
      materialKindCode = customer.getId();
      slvMaterialKindName.setTextContent(materialKindName);
      mainContent.setMaterialKindCode(materialKindCode);
      mainContent.setMaterialKindName(materialKindName);
    }
    if (requestCode == REQUEST_WAREHOUSE) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      String warehouseName = customer.getName();
      warehouseId = customer.getId();
      slvStorageName.setTextContent(warehouseName);
      mainContent.setStorageId(warehouseId);
      mainContent.setStorageName(warehouseName);
    }
    if (requestCode == REQUEST_INVOICETYPE) {
      //开票类型
      CustomerDialog content =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      slvInvoiceType.setTextContent(content.getName());
      mainContent.setInvoiceType(content.getId());
      mainContent.setInvoiceTypeName(content.getName());
    }
    if (requestCode == REQUEST_PERSON) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      String salePersonName = customer.getName();
      salePersonId = customer.getId();
      slvMoutappmanName.setTextContent(salePersonName);
      mainContent.setMoutappmanId(salePersonId);
      mainContent.setMoutappmanName(salePersonName);
    }
    if (requestCode == REQUEST_FILE) {
      String absolutePath = data.getStringExtra(ExtraUpLoadDialogFragment.EXTRA_ABSOLUTEPATH);
      //附件上传
      showDialog(FileUploadDialgFragment.newInstance(absolutePath, mainContent.getId(),
          "imsmm.r_outapp_main", false), REQUEST_UPLOAD);
    }
    if (requestCode == REQUEST_UPLOAD) {
      //附件上传成功
      String filePath = data.getStringExtra(FileUploadDialgFragment.EXTRA_PATH);
      slvFSelfinfo1.setTextContent(FileUtil.getFileNameByFilePath(filePath));
      //跟新附件路径
      mainContent.setFSelfinfo1(FileUtil.getFileNameByFilePath(filePath));
      mainContent.setFpSelfinfo1(filePath);
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      //保存并提交
      volleyPostSave(RUN);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  public static RetailOutMainDetailFragment newInstance(rOutappMain mainContent) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_PARAMS, mainContent);
    RetailOutMainDetailFragment fragment = new RetailOutMainDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }
}

